package cn.yeyiu.netonlinevideo.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import java.util.List;

import cn.yeyiu.netonlinevideo.R;
import cn.yeyiu.netonlinevideo.adapter.TypeListAdapter;
import cn.yeyiu.netonlinevideo.util.SourceObserver;
import cn.yeyiu.netonlinevideo.bean.SourceData;
import cn.yeyiu.netonlinevideo.bean.TypeData;
import cn.yeyiu.netonlinevideo.util.DataServer;

/**
 * 简单的一个 数据分类展示界面
 */
public class TypeListActivity extends AppCompatActivity {

    private ImageView backBtn;
    private TextView backTv;
    private RecyclerView rv;
    private ProgressBar progressBar;
    private TypeListAdapter adapter;

    private SourceData source;
    private DataServer dataGetter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_list);

        initData();
        bindView();
        bindEvent();
        initUI();
    }

    void initData() {
        source = JSONObject.parseObject(getIntent().getStringExtra("src"), SourceData.class);
        adapter = new TypeListAdapter(this);
        dataGetter = new DataServer(this, source.code);
    }

    void initUI() {
        backTv.setText(source.name);
        dataGetter.postTypeList();
    }

    void bindView() {
        backBtn = findViewById(R.id.back_btn);
        backTv = findViewById(R.id.back_tv);
        rv = findViewById(R.id.data_list_rv);
        progressBar = findViewById(R.id.progressBar);

        rv.setAdapter(adapter);
        rv.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
    }

    void bindEvent() {
        backBtn.setOnClickListener(v -> {
            finish();
        });

        dataGetter.setTypesChangeListener(new SourceObserver.TypesChangeListener() {
            @Override
            public void onTypesChange(List<TypeData> typeList) {
                progressBar.setVisibility(View.GONE);
                adapter.updateList(typeList);
            }
        });
    }
}